package pkg

import (
	"fmt"
	"math/rand"
	"net/url"
	"strings"
)

func GetBaseURL(urlStr string) (string, error) {
	parsed, err := url.Parse(urlStr)
	if err != nil {
		return "", err
	}

	baseURL := fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
	return baseURL, nil
}

// getStringValue 获取字符串值，处理指针类型
func GetStringValue(ptr *string) string {
	if ptr == nil {
		return ""
	}
	return *ptr
}

func GenerateRandom(length int) string {
	if length <= 0 || length > 8 {
		length = 4
	}
	const charset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

	result := make([]byte, length)
	for i := range result {
		result[i] = charset[rand.Intn(len(charset))]
	}
	return string(result)
}

func IsURL(filepath string) bool {
	return strings.HasPrefix(filepath, "http://") || strings.HasPrefix(filepath, "https://")
}
